package com.runen.infinitemovement.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.runen.infinitemovement.R;
import com.runen.infinitemovement.base.BaseActivity;
import com.runen.infinitemovement.model.api.CompanyAPI;
import com.runen.infinitemovement.model.api.UserAPI;
import com.runen.infinitemovement.model.base.BaseResponseEntity;
import com.runen.infinitemovement.model.entity.EventBusEntity;
import com.runen.infinitemovement.model.entity.PictrueEntity;
import com.runen.infinitemovement.tool.AppUtils;
import com.runen.infinitemovement.tool.CommonUtil;
import com.runen.infinitemovement.tool.GlideUtils;
import com.runen.infinitemovement.tool.UiUtil;
import com.runen.infinitemovement.widget.imageview.RoundedCornersImage;
import com.runen.infinitemovement.widget.popupwind.AddTopCorpsPoppupWindow;
import com.runen.rxnetlibrary.net.callback.BaseResultCallback;
import com.runen.rxnetlibrary.utils.PermissionUtils;
import com.runen.rxnetlibrary.utils.ToastUtils;
import com.runen.rxnetlibrary.utils.constant.PermissionConstants;
import com.runen.rxnetlibrary.utils.helper.DialogHelper;
import com.zhihu.matisse.Matisse;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class CrateCorpsActivity extends BaseActivity {
    @BindView(R.id.top_btn_left)
    Button topBtnLeft;
    @BindView(R.id.top_title)
    TextView topTitle;
    @BindView(R.id.v_title_line)
    View vTitleLine;
    @BindView(R.id.rl_camera)
    RelativeLayout rlCamera;
    @BindView(R.id.rci_corps_logo)
    RoundedCornersImage rciCorpsLogo;
    @BindView(R.id.iv_camera)
    ImageView ivCamera;
    @BindView(R.id.edt_corps_name)
    EditText edtCorpsName;
    @BindView(R.id.tv_sure_crate)
    TextView tvSureCrate;
    private List<Uri> avatar = new ArrayList<>();
    private int REQUEST_CODE_CHOOSE = 23;
    private String logo;
    private String corpsName, parentId;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_crate_corps;
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        ButterKnife.bind(this);
        parentId = getIntent().getStringExtra("parentId");
        topTitle.setText("创建新团队");
        vTitleLine.setVisibility(View.GONE);
    }


    @OnClick({R.id.top_btn_left, R.id.tv_sure_crate, R.id.rl_camera})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.top_btn_left:
                finish();
                break;
            case R.id.tv_sure_crate:
                showPopup();
                break;
            case R.id.rl_camera:
                onPermission();
                break;
        }
    }

    private AddTopCorpsPoppupWindow poppupWindow;

    private void showPopup() {
        corpsName = edtCorpsName.getText().toString().trim();
        if (TextUtils.isEmpty(logo)) {
            ToastUtils.showShort("请上传团队图标");
            return;
        }
        if (TextUtils.isEmpty(corpsName)) {
            ToastUtils.showShort("请输入团队名称");
            return;
        }
        poppupWindow = AddTopCorpsPoppupWindow.getInstance(this, logo, corpsName);
        poppupWindow.setOnHozonClickListener(new AddTopCorpsPoppupWindow.OnHozonClickListener() {
            @Override
            public void onHozomClick() {
                onSure();
            }
        });
        poppupWindow.show();
    }

    private void onSure() {
        JSONObject object = new JSONObject();
        try {
            object.put("parentId", parentId);
            object.put("teamName", corpsName);
            object.put("logo", logo);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        showDialog();
        new CompanyAPI().createOrEditingTeam(object.toString(), new BaseResultCallback<BaseResponseEntity<?>>() {
            @Override
            public void onResponse(BaseResponseEntity<?> response) {
                dismissDialog();
                if (response.getCode() == 0) {
                    poppupWindow.dismiss();
                    ToastUtils.showShort("创建成功");
                    // TODO: 2021/3/26
                    EventBus.getDefault().post(new EventBusEntity(4));
//                    startActivity(new Intent(CrateCorpsActivity.this, MainActivity.class));
//                    finish();
                    AppUtils.jumpToMain(CrateCorpsActivity.this);
                } else {
                    ToastUtils.showShort(response.getMessage());
                }
            }
        });
    }


    /**
     * 获取拍照权限
     */
    private void requestCamera() {
        UiUtil.getImageSelectorConfig(this, REQUEST_CODE_CHOOSE);
    }

    @SuppressLint("WrongConstant")
    private void onPermission() {
        //请求动态权限
        PermissionUtils.permission(
                PermissionConstants.STORAGE,
                PermissionConstants.CAMERA,
                PermissionConstants.WRITE_EXTERNAL_STORAGE,
                PermissionConstants.ACCESS_COARSE_LOCATION)
                .rationale(new PermissionUtils.OnRationaleListener() {
                    @Override
                    public void rationale(final ShouldRequest shouldRequest) {
                        DialogHelper.showRationaleDialog(shouldRequest);
                    }
                })
                .callback(new PermissionUtils.FullCallback() {
                    @Override
                    public void onGranted(List<String> permissionsGranted) {
                        requestCamera();
                    }

                    @Override
                    public void onDenied(List<String> permissionsDeniedForever,
                                         List<String> permissionsDenied) {
                        if (!permissionsDeniedForever.isEmpty()) {
                            DialogHelper.showOpenAppSettingDialog();
                        }
                    }
                })
                .request();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            if (data != null) {
                avatar = Matisse.obtainResult(data);
                if (avatar != null && avatar.size() > 0) {
                    Log.e("OnActivityResult ", String.valueOf(avatar.get(0)));
                    GlideUtils.loadImage(this, avatar.get(0).toString(), rciCorpsLogo);
                    ivCamera.setVisibility(View.GONE);
                    File file = null;
                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
                        file = CommonUtil.uriToFileApiQ(this, avatar.get(0));
                    } else {
                        file = CommonUtil.uri2File(this, avatar.get(0));
                    }
                    updateByImgUrl(file);
                }
            }
        }
    }


    private void updateByImgUrl(File imaUrl) {
        showDialog("上传图片中...", false);
        Log.e("OnActivityResult2 ", imaUrl.toString());
        TreeMap<String, String> mapType = new TreeMap<>();
        mapType.put("type", "headImg");
//        File file = ScreenShotHelper.compressImage2(CommonUtil.getImage(imaUrl.getPath()), this);
        TreeMap<String, File> mapFile = new TreeMap<>();
        mapFile.put("file", imaUrl);
        new UserAPI().putFile(mapType, mapFile, new BaseResultCallback<PictrueEntity>() {
            @Override
            public void onResponse(PictrueEntity response) {
                if (response.code == 0) {
                    dismissDialog();
                    if (response.data != null) {
                        Message message = new Message();
                        message.what = 1;
                        Bundle bundle = new Bundle();
                        bundle.putString("headImgUrl", response.data.url);
                        message.setData(bundle);
                        handler.sendMessage(message);
                    }
                }
            }
        });
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    Bundle bundle = msg.getData();
                    String headUrl = bundle.getString("headImgUrl");
                    logo = headUrl;
                    break;
            }
        }
    };

}